import React from "react";
import ReactDOM from "react-dom/client";

// 引入样式
import "./index.css";

class App extends React.PureComponent {
  listRef = React.createRef();

  state = {
    counter: 0,
    list: [],
  };

  componentDidMount() {
    // 计时器
    setInterval(() => {
      const newMsg = `Hello ${this.state.list.length + 1}`;

      this.setState({
        list: [newMsg, ...this.state.list],
      });
    }, 1000);
  }

  // 主要知识点，是在真实DOM更新之前能获取到上一次的滚条条相关的数据，就需要用到 getSnapshotBeforeUpdate

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // return {
    //   scrollTop: this.listRef.current.scrollTop,
    //   scrollHeight: this.listRef.current.scrollHeight,
    // };

    return this.listRef.current.scrollHeight;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // const addHeight = this.listRef.current.scrollHeight - snapshot.scrollHeight;
    // console.log("新增高度", addHeight);
    // console.log("上次的滚动距离", snapshot.scrollTop);
    // this.listRef.current.scrollTop = snapshot.scrollTop + addHeight;

    const addHeight = this.listRef.current.scrollHeight - snapshot;

    this.listRef.current.scrollTop += addHeight;
  }

  render() {
    return (
      <div className="list" ref={this.listRef}>
        {this.state.list.map((item, index) => {
          return (
            <div key={index} className="item">
              {item}
            </div>
          );
        })}
      </div>
    );
  }
}

ReactDOM.createRoot(document.querySelector("#root")).render(<App />);
